import {Component} from '@angular/core';
import {AlertController, IonicPage, NavController, NavParams} from 'ionic-angular';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {UserService} from "../../services/user.service";
import {MinerService} from "../../services/miner.service";
import {Setting} from "../../public/setting/setting";
import {Util} from "../../public/service/util";
import {Page} from "../../public/page";

@IonicPage()
@Component({
  selector: 'page-mill',
  templateUrl: 'mill.html',
})
export class MillPage {
  public myMiner: any;
  public minerList = [];//可升级矿机列表
  public isNormal: boolean = false;
  public isReactiveMill: boolean = false;
  public isUpgradeMill: boolean = false;
  public isRefresh: boolean = false;//是否刷新账户余额
  public type = {
    upgrade: 'UP',
    recast: 'RECAST',
  };
  payTypes: Array<{ key, val }> = [];
  enumStates = Setting.ENUMSTATE;
  public minerState: any = Setting.ENUMSTATE.minerState;
  public digState: any = Setting.ENUMSTATE.digState;
  public curSelectedMiner: any;//当前选择的矿机

  public upgradeMillValidateForm: FormGroup = this.fb.group({
    minerCode: [null, [Validators.required]],
    payType: [null, Validators.compose([Validators.required])],
  });
  public reactiveMillValidateForm: FormGroup = this.fb.group({
    payType: [null, Validators.compose([Validators.required])],
  });

  constructor(public navCtrl: NavController, public navParams: NavParams,
              private fb: FormBuilder, private alertCtrl: AlertController, private util: Util,
              private userService: UserService, private minerService: MinerService) {

  }


  ionViewDidLoad() {
    this.payTypes = this.util.getEnumDataList(Setting.ENUM.payTypes);
    this.getMinerList();//矿机
  }

  ionViewDidEnter() {
    this.getUserMiner();//我的矿机
  }

  /**
   * 我的矿机
   */
  getUserMiner() {
    this.userService.getUserMiner().then(data => {
      if (data) {
        this.myMiner = data;
        this.isNormal = true;
        if (this.myMiner.state === this.minerState.stop) this.curSelectedMiner = this.myMiner.minerItem;
      }
      else this.isNormal = false;
    })
  }

  getMinerList() {
    this.minerService.getMinerList(1, 20).then((data: Page) => {
      this.minerList = data.voList;
    })
  }

  optional(object) {
    this.isReactiveMill = false;//复投
    this.isUpgradeMill = false;//升级
    this.isRefresh = true;//请求账户余额
    this[object] = true;
  }

  beforeUpgradeMill($event) {
    $event.preventDefault();
    for (const key in this.upgradeMillValidateForm.controls) {
      this.getUpgradeMillFormControl(key).markAsDirty();
      this.getUpgradeMillFormControl(key).updateValueAndValidity();
    }
    if (this.upgradeMillValidateForm.invalid) return;
    this.passwordPrompt(this.type.upgrade);
  }

  beforeReactiveMill($event) {
    $event.preventDefault();
    for (const key in this.upgradeMillValidateForm.controls) {
      this.getUpgradeMillFormControl(key).markAsDirty();
      this.getUpgradeMillFormControl(key).updateValueAndValidity();
    }
    if (this.reactiveMillValidateForm.invalid) return;
    this.passwordPrompt(this.type.recast);
  }

  passwordPrompt(type) {
    this.isRefresh = false;
    let alert = this.alertCtrl.create({
      title: '交易密码',
      inputs: [
        {
          name: 'password',
          type: 'password',
          placeholder: '请输入交易密码'
        }
      ],
      buttons: [
        {
          text: '确认',
          handler: data => {
            if (!data.password || data.password === '') return false;
            else if (type === this.type.recast) {
              this.reactiveMill(data.password)
            } else if (type === this.type.upgrade) {
              this.upgradeMill(data.password)
            }
          }
        }
      ]
    });
    alert.present();
  }

  /**
   * 升级矿机
   * @param password
   */
  upgradeMill(password) {
    this.minerService.upgrade({
      payType: this.upgradeMillValidateForm.value.payType,
      minerCode: this.upgradeMillValidateForm.value.minerCode,
      pinPassword: password
    }).then(res => {
      //成功后隐藏表单，重新请求矿机数据
      this.isUpgradeMill = false;
      this.isRefresh = true;
      this.getUserMiner();
    })
  }

  /**
   * 复投矿机
   * @param password
   */
  reactiveMill(password) {
    this.minerService.recast({
      payType: this.reactiveMillValidateForm.value.payType,
      pinPassword: password
    }).then(res => {
      //成功后隐藏表单，重新请求矿机数据
      this.isReactiveMill = false;
      this.isRefresh = true;
      this.getUserMiner();
    })
  }

  /**
   * 收取金兰宝
   */
  harvest($event) {
    $event.preventDefault();
    this.userService.harvest().then(res => {
      this.getUserMiner();//收取成功刷新数据
    })
  }

  selectedMiner(code) {
    if(code) this.curSelectedMiner = this.minerList.find(item => item.code === code);
  }

  getUpgradeMillFormControl(name) {
    return this.upgradeMillValidateForm.controls[name];
  }

  getReactiveMillFormControl(name) {
    return this.reactiveMillValidateForm.controls[name];
  }

  cancelUpgrade() {
    this.isUpgradeMill = false;
    this.upgradeMillValidateForm.reset()
  }

  cancelReacttive() {
    this.isUpgradeMill = false;
    this.reactiveMillValidateForm.reset()
  }
}
